/**
 * 滑动窗口，类似438题。
 * @param {string} s
 * @param {string[]} words
 * @return {number[]}
 */
let findSubstring = function (s, words) {
    let res = [],
        sLen = s.length, wLen = words.length,
        wFirstLen = words[0].length

    for (let j = 0; j < wFirstLen; j++) {
        if (j + wLen * wFirstLen > sLen) return res

        // 初始化map，类似438题初始化36个英文字母
        let diffMap = new Map()
        for (let i = 0; i < wLen; i++) {
            let item = s.slice(j + i * wFirstLen, j + (i + 1) * wFirstLen)
            diffMap.set(item, (diffMap.get(item) || 0) + 1)
        }

        for (const word of words) {
            diffMap.set(word, (diffMap.get(word) || 0) - 1)
            if (diffMap.get(word) === 0) {
                diffMap.delete(word)
            }
        }

        // 如果为空，则匹配
        if (diffMap.size === 0) res.push(j)

        // 接着从下一个位置开始匹配
        for (let start = wFirstLen + j; start < sLen - wFirstLen + 1; start += wFirstLen) {
            // 上一个wFirstLen长度的s的值要滑走，所以减一。
            const previous = s.slice(start - wFirstLen, start)
            diffMap.set(previous, (diffMap.get(previous) || 0) - 1)
            if (diffMap.get(previous) === 0) {
                diffMap.delete(previous)
            }
            // 间隔wLen-1哥wFirstLen长度的下一个   长度为wFirstLen长度的s的值要滑入，所以加一。
            const current = s.slice(start + wFirstLen * (wLen - 1), start + wFirstLen * wLen)
            diffMap.set(current, (diffMap.get(current) || 0) + 1)
            if (diffMap.get(current) === 0) {
                diffMap.delete(current)
            }

            // 滑完一次判断一下
            if (diffMap.size === 0) res.push(start)
        }
    }
    return res
};
console.log(findSubstring("asbarfoothefoobarmanbarfoo", ["foo", "bar"]))